package com.gj.tourismcommunity.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.Arrays;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    
    /**
     * 密码编码器
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    
    /**
     * 安全过滤器链配置
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .csrf(csrf -> csrf.disable())
                .cors(cors -> cors.configurationSource(corsConfigurationSource()))
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/api/auth/**").permitAll()
                        .requestMatchers("/error").permitAll()
                        .anyRequest().authenticated()
                );

        return http.build();
    }

    /**
     * CORS配置
 * 该方法用于配置跨域资源共享(CORS)的规则，通过创建CorsConfigurationSource Bean来实现
 * 配置了允许的源、方法、头部信息以及是否允许凭证等跨域相关设置
     */
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
    // 创建CorsConfiguration对象，用于存放CORS的具体配置信息
        CorsConfiguration configuration = new CorsConfiguration();
    // 设置允许的源模式，这里使用通配符"*"表示允许所有来源
        configuration.setAllowedOriginPatterns(Arrays.asList("*"));
    // 设置允许的HTTP方法，包括GET、POST、PUT、DELETE和OPTIONS
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
    // 设置允许的请求头，使用通配符"*"表示允许所有请求头
        configuration.setAllowedHeaders(Arrays.asList("*"));
    // 设置允许发送凭证信息，如cookies、HTTP认证等
        configuration.setAllowCredentials(true);

    // 创建UrlBasedCorsConfigurationSource对象，用于注册CORS配置
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    // 将配置注册到所有路径("/**")上
        source.registerCorsConfiguration("/**", configuration);
    // 返回配置完成的CORS源
        return source;
    }
}